/**
 * 诗人选择器组件
 * 负责管理诗人角色的选择、切换和信息显示
 */

import { ProgressManager } from './ProgressManager.js';

export class PoetSelector {
    constructor(apiUrl, poet3DCharacter = null, progressManager = null) {
        this.apiUrl = apiUrl;
        this.currentPoet = 'liqingzhao'; // 默认诗人
        this.poets = {};
        this.poetGrid = null;
        this.currentPoetInfo = null;
        this.poet3DCharacter = poet3DCharacter;
        
        // 进度管理器（可选，如果未提供则创建默认实例）
        this.progressManager = progressManager || new ProgressManager();
        
        this.init();
    }

    async init() {
        try {
            // 获取DOM元素
            this.poetDropdown = document.getElementById('poet-dropdown');
            this.currentPoetInfo = document.getElementById('current-poet-info');
            
            if (!this.poetDropdown) {
                console.error('找不到诗人下拉选择元素');
                return;
            }
            
            // 加载诗人数据
            await this.loadPoets();
            
            // 渲染诗人下拉选择栏
            this.renderPoetDropdown();
            
            // 绑定下拉选择事件
            this.bindDropdownEvents();
            
            // 加载当前诗人
            await this.loadCurrentPoet();
            
            // 设置默认诗人（如果没有当前诗人）
            if (!this.currentPoet && Object.keys(this.poets).length > 0) {
                const firstPoetId = Object.keys(this.poets)[0];
                await this.selectPoet(firstPoetId);
            }
            
        } catch (error) {
            console.error('诗人选择器初始化失败:', error);
            throw error;
        }
    }

    /**
     * 加载所有诗人信息
     */
    async loadPoets() {
        try {
            const url = `${this.apiUrl}/poets`;
            console.log('正在请求诗人数据:', url);
            
            const response = await fetch(url);
            console.log('API响应状态:', response.status, response.statusText);
            
            if (!response.ok) {
                throw new Error(`获取诗人列表失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            this.poets = data.poets || {};
            console.log('加载诗人数据成功:', this.poets);
        } catch (error) {
            console.error('加载诗人数据失败:', error);
            console.log('使用默认诗人数据作为备用');
            // 使用默认数据作为备用
            this.poets = this.getDefaultPoets();
        }
    }

    /**
     * 获取默认诗人数据（备用）
     */
    getDefaultPoets() {
        return {
            liqingzhao: {
                name: '李清照',
                dynasty: '宋朝',
                style: '婉约派',
                personality: '才华横溢、情感细腻、坚韧不屈'
            },
            libai: {
                name: '李白',
                dynasty: '唐朝',
                style: '浪漫主义',
                personality: '豪放不羁、天真浪漫、才华横溢'
            },
            dufu: {
                name: '杜甫',
                dynasty: '唐朝',
                style: '现实主义',
                personality: '忧国忧民、严谨治学、仁爱宽厚'
            },
            sushi: {
                name: '苏轼',
                dynasty: '宋朝',
                style: '豪放派',
                personality: '豁达乐观、才华全面、幽默风趣'
            },
            taoyuanming: {
                name: '陶渊明',
                dynasty: '东晋',
                style: '田园诗派',
                personality: '淡泊名利、热爱自然、真诚质朴'
            }
        };
    }

    /**
     * 渲染诗人下拉选择栏
     */
    renderPoetDropdown() {
        if (!this.poetDropdown) return;

        // 清空现有选项（保留默认选项）
        const defaultOption = this.poetDropdown.querySelector('option[value=""]');
        this.poetDropdown.innerHTML = '';
        if (defaultOption) {
            this.poetDropdown.appendChild(defaultOption);
        }

        // 添加诗人选项
        Object.entries(this.poets).forEach(([poetId, poetInfo]) => {
            const option = document.createElement('option');
            option.value = poetId;
            option.textContent = `${poetInfo.name} (${poetInfo.dynasty})`;
            this.poetDropdown.appendChild(option);
        });
    }

    /**
     * 绑定下拉选择事件
     */
    bindDropdownEvents() {
        if (!this.poetDropdown) return;

        this.poetDropdown.addEventListener('change', (event) => {
            const selectedPoetId = event.target.value;
            if (selectedPoetId) {
                this.selectPoet(selectedPoetId);
            }
        });
    }



    /**
     * 选择诗人
     */
    async selectPoet(poetId) {
        if (poetId === this.currentPoet) return;

        try {
            // 开始进度管理
            this.progressManager.startLoading();
            this.progressManager.updateProgress(10, `开始切换到诗人 ${poetId}...`);
            
            // 更新UI状态
            this.updateDropdownSelection(poetId);
            
            // 调用后端API切换诗人
            this.progressManager.updateProgress(20, `正在调用后端API切换诗人...`);
            await this.switchPoetOnBackend(poetId);
            
            // 更新当前诗人
            this.currentPoet = poetId;
            
            // 切换3D角色模型
            if (this.poet3DCharacter) {
                try {
                    this.progressManager.updateProgress(30, `开始切换3D角色模型到: ${poetId}`);
                    console.log(`开始切换3D角色模型到: ${poetId}`);
                    const modelSwitchSuccess = await this.poet3DCharacter.switchToPoet(poetId, {
                        playGreeting: true,
                        externalProgressControl: true  // 外部控制进度，避免重复管理
                    });
                    
                    if (modelSwitchSuccess) {
                        console.log(`3D角色模型切换成功: ${poetId}`);
                        this.progressManager.updateProgress(90, `3D角色模型切换成功`);
                    } else {
                        console.warn(`3D角色模型切换失败: ${poetId}`);
                        this.progressManager.updateProgress(90, `3D角色模型切换失败`);
                    }
                } catch (modelError) {
                    console.error('3D角色模型切换时发生错误:', modelError);
                    this.progressManager.updateProgress(90, `3D角色模型切换时发生错误`);
                }
            }
            
            // 更新诗人信息显示
            this.progressManager.updateProgress(95, `更新诗人信息显示...`);
            this.updateCurrentPoetInfo();
            
            // 触发自定义事件
            this.dispatchPoetChangeEvent(poetId);
            
            console.log(`已切换到诗人: ${poetId}`);
            
            // 完成进度
            this.progressManager.updateProgress(100, `诗人 ${poetId} 切换完成`);
            // ProgressManager会在500ms后自动调用hide()，无需重复调用
            
        } catch (error) {
            console.error('切换诗人失败:', error);
            // 恢复原来的选中状态
            this.updateDropdownSelection(this.currentPoet);
            
            // 进度失败
            this.progressManager.updateProgress(100, `切换诗人失败`);
            // ProgressManager会在500ms后自动调用hide()，无需重复调用
        }
    }

    /**
     * 更新下拉选择器的选中状态
     */
    updateDropdownSelection(poetId) {
        if (!this.poetDropdown) return;
        
        // 设置下拉选择器的值
        this.poetDropdown.value = poetId;
    }

    /**
     * 调用后端API切换诗人
     */
    async switchPoetOnBackend(poetId) {
        try {
            const response = await fetch(`${this.apiUrl}/poet/switch/${poetId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`切换诗人失败: ${response.statusText}`);
            }

            const result = await response.json();
            return result;
        } catch (error) {
            console.error('切换诗人失败:', error);
            throw error;
        }
    }

    /**
     * 加载当前诗人信息
     */
    async loadCurrentPoet() {
        try {
            const response = await fetch(`${this.apiUrl}/poet/current`);
            if (response.ok) {
                const data = await response.json();
                if (data.current_poet) {
                    this.currentPoet = data.current_poet;
                    this.updateActiveCard(this.currentPoet);
                    this.updateCurrentPoetInfo();
                }
            }
        } catch (error) {
            console.warn('获取当前诗人信息失败:', error);
        }
    }
    
    /**
     * 更新激活的诗人卡片
     */
    updateActiveCard(poetId) {
        console.log(`更新激活的诗人卡片: ${poetId}`);
        
        // 移除所有卡片的激活状态
        const cards = this.selector.querySelectorAll('.poet-card');
        cards.forEach(card => {
            card.classList.remove('active');
        });
        
        // 为选中的诗人卡片添加激活状态
        const activeCard = this.selector.querySelector(`.poet-card[data-poet="${poetId}"]`);
        if (activeCard) {
            activeCard.classList.add('active');
            console.log(`✅ 诗人卡片 ${poetId} 已激活`);
        } else {
            console.warn(`⚠️ 未找到诗人 ${poetId} 的卡片`);
        }
    }

    /**
     * 更新当前诗人信息显示
     */
    updateCurrentPoetInfo() {
        if (!this.currentPoetInfo) return;

        const poetInfo = this.poets[this.currentPoet];
        if (!poetInfo) return;

        // 更新头像显示
        const avatarElement = this.currentPoetInfo.querySelector('.poet-avatar-display');
        if (avatarElement) {
            avatarElement.className = `poet-avatar-display poet-avatar-circle ${this.currentPoet}`;
        }

        // 更新诗人信息
        const nameElement = this.currentPoetInfo.querySelector('.poet-name');
        const dynastyElement = this.currentPoetInfo.querySelector('.poet-dynasty');
        const styleElement = this.currentPoetInfo.querySelector('.poet-style');

        if (nameElement) nameElement.textContent = poetInfo.name || this.currentPoet;
        if (dynastyElement) dynastyElement.textContent = poetInfo.dynasty || '';
        if (styleElement) styleElement.textContent = poetInfo.style || '';

        // 更新背景样式
        this.currentPoetInfo.className = `current-poet-info ${this.currentPoet}`;
    }

    /**
     * 触发诗人切换事件
     */
    dispatchPoetChangeEvent(poetId) {
        const event = new CustomEvent('poetChanged', {
            detail: {
                poetId: poetId,
                poetInfo: this.poets[poetId]
            }
        });
        document.dispatchEvent(event);
    }

    /**
     * 获取当前诗人ID
     */
    getCurrentPoet() {
        return this.currentPoet;
    }

    /**
     * 获取诗人信息
     */
    getPoetInfo(poetId) {
        return this.poets[poetId];
    }

    /**
     * 销毁组件
     */
    destroy() {
        // 清理事件监听器等
        if (this.poetDropdown) {
            this.poetDropdown.removeEventListener('change', this.bindDropdownEvents);
            this.poetDropdown.innerHTML = '';
        }
    }
}